package zy.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import zy.util.CommonUtil;

public class LoginInterceptor implements HandlerInterceptor {
	private static final String LOGIN_URL = "/toIndex";
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object arg2, Exception arg3)
			throws Exception {
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response,
			Object arg2, ModelAndView arg3) throws Exception {
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object arg2) throws Exception {
		HttpSession session = request.getSession(true);
		Object obj = session.getAttribute(CommonUtil.KEY_USER);
		Object obj2 = session.getAttribute(CommonUtil.KEY_MENU);
		if(null == obj || "".equals(obj.toString()) || null == obj2){
			if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")){ //如果是ajax请求响应头会有，x-requested-with  
	            response.setHeader("sessionstatus", "timeout");//在响应头设置session状态  
	        }else{
	        	response.sendRedirect(request.getContextPath() + LOGIN_URL);
	        }
			return false;
		}
		return true;
	}

}
